// 监听来自父窗口的消息
window.addEventListener('message', function(event) {
    // 确保消息来源是可信的
    const allowedOrigins = ['127.0.0.1', 'localhost', 'test-tds-standard.cepin.com'];
    if (!allowedOrigins.some(origin => event.origin.includes(origin))) {
        console.log('Rejected message from:', event.origin);
        return;
    }

    console.log('Received message:', event.data);
    const { type, data, token, userInfo } = event.data;

    if (type === 'SETUP_TOKEN') {
        console.log('Setting up token...');
        try {
            // 设置token和用户信息
            localStorage.setItem('tds-token', token);
            localStorage.setItem('tds-userInfo', JSON.stringify(userInfo));
            console.log('Token and userInfo set successfully');
            console.log('Current localStorage:', {
                'tds-token': localStorage.getItem('tds-token'),
                'tds-userInfo': localStorage.getItem('tds-userInfo')
            });

            // 立即通知父窗口设置成功
            window.parent.postMessage({
                type: 'TOKEN_SETUP_SUCCESS'
            }, '*');

            // 等待一会儿再跳转，确保消息已发送
            setTimeout(() => {
                console.log('Navigating to target page...');
                window.location.href = 'https://test-tds-standard.cepin.com/tds/#/tissue-analysis/portrait';
            }, 100);
        } catch (error) {
            console.error('Error setting up token:', error);
            // 通知父窗口错误
            window.parent.postMessage({
                type: 'ERROR',
                error: error.message
            }, '*');
        }
    }
    else if (type === 'SET_TOKEN') {
        console.log('Setting token');
        localStorage.setItem('tds-token', token);
        console.log('Token has been set');
    }
    else if (type === 'SET_LOCAL_STORAGE') {
        console.log('Setting localStorage data');
        Object.entries(data).forEach(([key, value]) => {
            localStorage.setItem(key, value);
            console.log(`${key} has been set`);
        });
        
        // 触发页面刷新以应用新的token
        console.log('Scheduling page reload');
        setTimeout(() => {
            window.location.href = '/tds/#/tissue-analysis/portrait';
        }, 1000);
    }
}); 